package com.ljm.sys.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljm.common.constants.SecurityConstants;
import com.ljm.common.dto.UserInfoDto;
import com.ljm.common.enums.DataStatus;
import com.ljm.common.page.PageDto;
import com.ljm.security.util.UserUtil;
import com.ljm.sys.auth.api.SysAuthUserRoleApi;
import com.ljm.sys.auth.dto.UserRefDto;
import com.ljm.sys.auth.entity.SysAuthUserRole;
import com.ljm.sys.auth.mapper.SysAuthUserRoleMapper;
import com.ljm.sys.auth.service.ISysAuthUserRoleService;
import com.ljm.sys.org.dto.SysOrgUserDto;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * <p>
    * 系统用户角色关联 服务实现类
    * </p>
 *
 * @author HuamingChen
 * @since 2020-06-11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysAuthUserRoleServiceImpl extends ServiceImpl<SysAuthUserRoleMapper, SysAuthUserRole>
        implements ISysAuthUserRoleService, SysAuthUserRoleApi {
    @Resource
    private SysAuthUserRoleMapper sysAuthUserRoleMapper;
    @Override
    public void userRefRole(ArrayList<String> roleCodes, Long userId, UserInfoDto curUser) {
        //删除用户拥有的角色
        LambdaQueryWrapper<SysAuthUserRole> wrapper = new LambdaQueryWrapper<>();
        if(!UserUtil.getRole().contains(SecurityConstants.ROLE_ADMIN)){
            wrapper.eq(SysAuthUserRole::getOrgId,curUser.getOrgId());
        }
        wrapper.eq(SysAuthUserRole::getUserId,userId);
        this.remove(wrapper);

        //新增权限
        if(CollectionUtils.isNotEmpty(roleCodes)){
            List<SysAuthUserRole> userRoleList=new ArrayList<>();
            roleCodes.forEach(roleCode->{
                SysAuthUserRole userRole=new SysAuthUserRole();
                userRole.setCreater(curUser.getLoginName());
                userRole.setCreateTime(LocalDateTime.now());
                userRole.setOrgId(curUser.getOrgId());
                userRole.setStatus(DataStatus.NORMAL.getCode());
                userRole.setIsDelete(false);
                userRole.setUserId(userId);
                userRole.setRoleCode(roleCode);
                userRoleList.add(userRole);
            });
            this.saveBatch(userRoleList);
        }
    }

    @Override
    public Set<String> getDataByUserId(Long userId) {
        List<SysAuthUserRole> list = this.list(new LambdaQueryWrapper<SysAuthUserRole>().eq(SysAuthUserRole::getUserId, userId));
        if(CollectionUtils.isNotEmpty(list)){
            return list.stream().map(SysAuthUserRole::getRoleCode).collect(Collectors.toSet());
        }else{
            return Collections.emptySet();
        }
    }

    @Override
    public void roleRefUser(String roleCode, Set<Long> userIds) {
        //删除用户拥有的角色
        LambdaQueryWrapper<SysAuthUserRole> wrapper = new LambdaQueryWrapper<>();
        if(!UserUtil.getRole().contains(SecurityConstants.ROLE_ADMIN)){
            wrapper.eq(SysAuthUserRole::getOrgId,UserUtil.getCurUser().getOrgId());
        }
        wrapper.eq(SysAuthUserRole::getRoleCode,roleCode);
        wrapper.in(SysAuthUserRole::getUserId,userIds);
        this.remove(wrapper);
        if(CollectionUtils.isNotEmpty(userIds)){
            List<SysAuthUserRole> userRoleList=new ArrayList<>();
            userIds.forEach(userId->{
                SysAuthUserRole userRole=new SysAuthUserRole();
                userRole.setCreater(UserUtil.getLoginName());
                userRole.setCreateTime(LocalDateTime.now());
                userRole.setOrgId(UserUtil.getCurUser().getOrgId());
                userRole.setStatus(DataStatus.NORMAL.getCode());
                userRole.setIsDelete(false);
                userRole.setUserId(userId);
                userRole.setRoleCode(roleCode);
                userRoleList.add(userRole);
            });
            this.saveBatch(userRoleList);
        }
    }

    @Override
    public void setUserRoleRef(UserRefDto dto) {
        this.roleRefUser(dto.getRoleCode(),dto.getUserIds());
    }

    @Override
    public PageDto<SysOrgUserDto> getRoleRefUser(String realName, String roleCode, String loginName, String email, Integer pageNo, Integer pageSize) {
        PageDto<SysOrgUserDto> pageDto=new PageDto<>(pageNo,pageSize);
        Long roleRefUserCount = sysAuthUserRoleMapper.getRoleRefUserCount(realName, roleCode, loginName, email);
        if(roleRefUserCount>0){
            List<SysOrgUserDto> roleRefUserData = sysAuthUserRoleMapper.getRoleRefUserData(realName, roleCode, loginName, email, (pageNo - 1) * pageSize, pageSize);
            if(CollectionUtils.isNotEmpty(roleRefUserData)){
                pageDto.setTotal(roleRefUserCount);
                pageDto.setRecords(roleRefUserData);
            }
        }else{
            pageDto.setTotal(0L);
        }
        return pageDto;
    }

    @Override
    public void delRoleRefUser(List<Long> ids) {
        this.removeByIds(ids);
    }
}
